package com.example.loginpilot_01.service.user;

import com.example.loginpilot_01.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    // 构造方法注入UserRepository
    public UserDetailsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 核心方法：根据用户名查询用户，并封装为Spring Security识别的UserDetails
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询数据库中的用户
        User user = userRepository.findByUsername(username);
        if (user == null) {
            // 用户名不存在，抛出异常（Spring Security会自动处理为“登录失败”）
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 2. 封装用户角色（Spring Security需要GrantedAuthority类型）
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以“ROLE_”开头（如ROLE_USER、ROLE_ADMIN），与User实体的role字段一致
        authorities.add(new SimpleGrantedAuthority(user.getRole()));

        // 3. 返回Spring Security的User对象（包含用户名、加密密码、角色权限）
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(), // 数据库中已加密的密码，Spring Security会自动匹配
                authorities // 用户的角色权限集合
        );
    }
}